﻿using Microsoft.AspNetCore.Http;
using System;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace RuoVea.ExWeb.SafeList
{
    /// <summary>
    /// 限制指定IP访问 中间键
    /// </summary>
    public class SafeListMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly string _safelist;

        /// <summary>
        /// 限制指定IP访问
        /// </summary>
        /// <param name="next"></param>
        /// <param name="safelist"></param>
        public SafeListMiddleware(RequestDelegate next, string safelist)
        {
            _safelist = safelist;
            _next = next;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Method != HttpMethod.Get.Method)
            {
                var remoteIp = context.Connection.RemoteIpAddress;
                string[] ip = _safelist.Split(';');
                var bytes = remoteIp.GetAddressBytes();
                var badIp = true;
                foreach (var address in ip)
                {
                    var testIp = System.Net.IPAddress.Parse(address);
                    if (testIp.GetAddressBytes().SequenceEqual(bytes))
                    {
                        badIp = false;
                        break;
                    }
                }
                if (badIp)
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                    return;
                }
            }
            await _next.Invoke(context);
        }
    }
}
